package com.winning.gjhlht.ihe.job.thread;

import com.cownew.ctk.common.RandomGUID;
import com.framework.helper.ServerSQLExecutorUtils;
import com.framework.server.manager.SQLConfigLoader;
import com.winning.common.Constans;
import com.winning.gjhlht.bean.InterfaceConfigBean;
import com.winning.gjhlht.ihe.cdaService.service.IBaseCDACreaterServiceInter;
import com.winning.gjhlht.ihe.common.IHEConstans;
import org.apache.log4j.Logger;

import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * 重庆渝中互联互通批量生成CDA文档线程
 *
 * @author z_dd@winning.com.cn
 * @date 2019/3/1 13:45
 */
public class HLHTCreateCDARequestTask extends TimerTask {

    private static Logger LOGGER = Logger.getLogger(Constans.LOG4J_PBS_LOGGER_ID);

    //判断线程是否执行完毕
    private boolean isOver = false;

    //接口配置信息
    private InterfaceConfigBean configBean;

    //数据源
    private String dbDataSourceID = "Default_SQL_Dev";

    private IBaseCDACreaterServiceInter baseCDACreaterService = null;

    private List<Map<String, Object>> registrationRequestInfoDataList = null;
    //业务表数据源

    public HLHTCreateCDARequestTask(List<Map<String, Object>> registrationRequestInfoDataList, IBaseCDACreaterServiceInter baseCDACreaterService, InterfaceConfigBean configBean) {
        this.registrationRequestInfoDataList = registrationRequestInfoDataList;
        this.baseCDACreaterService = baseCDACreaterService;
        this.configBean = configBean;
    }

    public boolean isOver() {
        return isOver;
    }

    @Override
    public void run() {
        try {
            //填充所有信息, 并发送请求
            for (Iterator<Map<String, Object>> iterator = registrationRequestInfoDataList.iterator(); iterator.hasNext(); )
                if (iterator != null) {
                    //一个请求的基本信息, key值为表字段名称，统一为大写
                    Map<String, Object> map = iterator.next();

                    if (map != null) {
                        //个人基本标识号
                        String grjbbsh = (String) map.get(IHEConstans.KEY_PERSION_REGISTER_GRJBXXBSH);

                        //身份证号
                        String zjhm = (String) map.get(IHEConstans.KEY_PERSION_REGISTER_ZJHM);

                        //机构代码
                        String jgbm = (String) map.get(IHEConstans.KEY_PERSION_REGISTER_YLJGDM);

                        //国家平台唯一标识号
                        String gjptbsh = (String) map.get(IHEConstans.KEY_JBXX_REGISTER_GJPTBSH);

                        //患者姓名
                        String xm = (String) map.get(IHEConstans.KEY_PERSION_REGISTER_XM);

                        //全球唯一ID
                        String requestID = UUID.randomUUID().toString().replaceAll("-", "");
                        map.put("REQUESTID", requestID);

                        //cda模板文件名称，路径已经固定。
                        String cdaTempFileName = configBean.getCdaTempFileName();

                        String basicSQL = SQLConfigLoader.getSQLByID(configBean.getSQLByID()) + " where a.GRJBXXBSH = ?";

                        Object[] param = new Object[]{grjbbsh};


                        //根据提供的一个患者的SQL，查询患者的健康档案信息，再根据CDA模板生成标准的CDA文档
                        Map<String, Object> cdaDocumentContenValue = baseCDACreaterService.createOneCDADocumentService(xm, requestID, cdaTempFileName, map);

                        //生成CDA文档返回结果信息
                        //LOGGER.info("--> 返回创建CDA文档信息 ："+cdaDocumentContenValue.toString());

                        //3、将生成的CDA文档和其他基本信息保存到：CDA文档缓存表<IHE_CDA_DOC_BUFFER>
                        if (cdaDocumentContenValue != null) {

                            String cdaDocumentStr = cdaDocumentContenValue.get("cdaDocument").toString();

                            if (cdaDocumentStr == null || cdaDocumentStr.equals("")) {
                                LOGGER.info("--> 创建CDA的文档为空 ，无法写入数据库");
                                return;
                            }

                            HashMap<String, Object> paramCDA = new HashMap<String, Object>();


                            paramCDA.put("Id", requestID);

                            paramCDA.put("SourcePatientID", grjbbsh);

                            paramCDA.put("SourcePatientName", xm);

                            paramCDA.put("IdentityId", zjhm);

                            paramCDA.put("UniqueId", requestID);

                            paramCDA.put("DocumentId", new RandomGUID().toString());

                            paramCDA.put("Title", configBean.getName());
                            paramCDA.put("WDLX", configBean.getCategory());

                            //管理机构名称
                            paramCDA.put("SONAME", map.get("WDGLJGMC"));
                            //管理机构代码
                            paramCDA.put("SOCODE", map.get("WDGLJGDM"));
                            //YLJGMC医疗机构代码
                            paramCDA.put("ONAME", map.get("YLJGMC"));
                            //YLJGDM医疗机构名称
                            paramCDA.put("OID", map.get("YLJGDM"));
                            //流水号
                            paramCDA.put("EPISODEID", map.get("EPISODEID"));
                            //


                            //验证结果
                            if (cdaDocumentContenValue.containsKey("YZJG")) {
                                paramCDA.put("YZJG", cdaDocumentContenValue.get("YZJG").toString());
                            }
                            if (cdaDocumentContenValue.containsKey("YZJGSM")) {
                                paramCDA.put("YZJGSM", cdaDocumentContenValue.get("YZJGSM").toString());
                            }


                            LOGGER.info("-->需要转化成Base64的CDA文档:" + cdaDocumentStr);

                            //转base64编码
                            String base64Str = getBASE64(cdaDocumentStr);


                            if (base64Str == null || base64Str.equals("")) {
                                LOGGER.info("-->CDA文档转换Base64编码错误");
                                return;
                            }
                            paramCDA.put("CONTENT", base64Str);
                            paramCDA.put("xmlContent", cdaDocumentStr);

                            //将cda信息保存到数据库
                            int result = saveCDADOCBUFFER(paramCDA);

                            if (result != -1) {
                                LOGGER.info("--> CDA信息到表 IHE_CDA_DOC_BUFFER 成功");
                            } else {
                                LOGGER.info("--> CDA信息到表 IHE_CDA_DOC_BUFFER 失败");
                            }

                        }
                    }

                }
            registrationRequestInfoDataList.removeAll(registrationRequestInfoDataList);
            registrationRequestInfoDataList = null;
        } catch (Exception e) {
            //打印异常堆栈信息
            LOGGER.error(e, e.fillInStackTrace());
            e.printStackTrace();
        } finally {
            //线程结束状态
            isOver = true;

            System.gc();
        }

    }

    public static String getBASE64(String cdaContentValue) {

        try {
            String base64Str = "";

            if (cdaContentValue == null) {
                return null;
            }

            try {
                base64Str = (new sun.misc.BASE64Encoder()).encode(cdaContentValue.getBytes("UTF-8")).replace("\n", "").replace("\r", "");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            return base64Str;
        } catch (Exception e) {
            LOGGER.error(e, e.fillInStackTrace());
        }

        return null;
    }

    private int saveCDADOCBUFFER(HashMap<String, Object> map) {
        try {
            //拼接插入SQL语句
            //填充信息
            Object[] params = new Object[map.size()];

            String insertSQL = "INSERT INTO IHE_CDA_DOC_BUFFER (";

            //参数个数标记
            int index = 0;

            //根据个人信息map表动态填充insert语句
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                String key = entry.getKey();
                Object value = entry.getValue();

                insertSQL += key + ",";

                params[index] = value;

                index++;

            }

            //添加创建时间createTime
            insertSQL += "CreateTime ";

            insertSQL += ") VALUES (";

            for (int i = 0; i < index; i++) {
                insertSQL += "?,";
            }

//			//去除最后一个  ，符号
//			insertSQL = insertSQL.substring(0,insertSQL.length()-1);

            //判断是否有OR
            if (dbDataSourceID.indexOf(Constans.DATA_SOURCE_ORACLE_TAG) > -1) {
                insertSQL += "sysdate ";
            } else {
                insertSQL += "getdate() ";
            }
            //添加创建时间createTime


            insertSQL += ")";

            LOGGER.info("-->新增SQL语句" + insertSQL);
            LOGGER.info("-->参数:" + params.toString());

            ServerSQLExecutorUtils.execute(insertSQL, params, dbDataSourceID);

            LOGGER.info("-->新增成功");
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error(e.getMessage());
        }
        return -1;
    }
}
